package com.example.forum.controller;

import com.example.forum.service.imp.UserServiceImp;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;

@RestController
public class FileUploadController {
    @Autowired
    private UserServiceImp userServiceImp;

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/uploadAvatar")
    public ResponseEntity<Map<String, Object>> uploadAvatar(@RequestParam("file") MultipartFile file, @RequestParam("userId") Long userId) {
        Map<String, Object> response = new HashMap<>();
        if (file.isEmpty()) {
            response.put("code", 1);
            response.put("message", "文件为空");
            return ResponseEntity.badRequest().body(response);
        }

        try {
            // 创建上传目录
            File dir = new File(uploadDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            // 生成文件名
            String fileName = System.currentTimeMillis() + "_" + file.getOriginalFilename();
            Path path = Paths.get(uploadDir + fileName);

            // 保存文件
            Files.copy(file.getInputStream(), path);

            // 保存头像路径到数据库
            String avatarUrl = "/uploads/avatars/" + fileName;
            userServiceImp.updateUserAvatar(userId, avatarUrl);

            // 返回成功响应
            response.put("code", 0);
            response.put("message", "上传成功");
            response.put("data", Map.of("filePath", avatarUrl));
            return ResponseEntity.ok(response);
        } catch (IOException e) {
            e.printStackTrace();
            response.put("code", 1);
            response.put("message", "文件上传失败");
            return ResponseEntity.status(500).body(response);
        }
    }
}
